/*
 * Famon (http://code.google.com/p/famon/)
 * Copyright (c) 2010 Carl Crous.
 *
 * This file is part of Famon.
 *
 * Famon is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Famon is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Famon.  If not, see <http://www.gnu.org/licenses/>.
 */

package za.org.foobar.famon.frontend.server.util;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import org.gwtportlets.portlet.smartgwt.client.CriteriaDto;
import org.gwtportlets.portlet.smartgwt.server.SmartFilter;
import za.org.foobar.famon.frontend.client.FamonException;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author Carl Crous
 */
public class ServerUtil {

    public static Key getKeyFromCriteria(CriteriaDto c, Class cls, String idField) {
        String id = SmartFilter.getSimpleCriteriaValue(c, idField);
        if (id == null) {
            throw new FamonException("No failureId provided in request");
        }
        return KeyFactory.createKey(cls.getSimpleName(), Long.parseLong(id));
    }

    public static Key getKeyFromCriteria(CriteriaDto c, Key parent, Class cls, String idField) {
        String id = SmartFilter.getSimpleCriteriaValue(c, idField);
        if (id == null) {
            throw new FamonException("No failureId provided in request");
        }
        return KeyFactory.createKey(parent, cls.getSimpleName(), Long.parseLong(id));
    }

    public static <T> T isNull(T value, T defaultValue) {
        return value != null ? value : defaultValue;
    }

    public static String urlEncode(String str) {
        if (str == null) {
            return null;
        }
        try {
            return URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return str;
        }
    }

    public static String urlDecode(String str) {
        if (str == null) {
            return null;
        }
        try {
            return URLDecoder.decode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return str;
        }
    }
}
